package com.demo.shufflingpicture;

import java.util.LinkedList;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
/**
 * 轮播图
 * 
 * @author fuxingkai
 * 
 */
public class ShufflingPicture extends RelativeLayout implements OnPageChangeListener, OnTouchListener{

	private Context context;
	private ViewPager imageViewPager;
	private AdapterCycle pagerAdapter;
	private LinearLayout pointLinearLayout;
	private LinkedList<View> views;
	private ImageView[] points;
	private Drawable pointDrawableNoraml;
	private Drawable pointDrawableSelect;
	private boolean isPlay = true;
	private boolean left = false;
	private boolean right = false;
	private boolean isScrolling = false;
	private int currentIndex = 0;
	private int pointIndex = 1;
	private int lastValue = -1;
	private ChangeViewCallback changeViewCallback = null;

	public ShufflingPicture(Context context) {
		super(context);
		this.context = context;
		initView();
	}

	public ShufflingPicture(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		initView();
		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.ShufflingPicture);
		pointDrawableNoraml = a.getDrawable(R.styleable.ShufflingPicture_pointDrawbleNormal);
		pointDrawableSelect = a.getDrawable(R.styleable.ShufflingPicture_pointDrawbleSelect);
		if (pointDrawableNoraml == null) {
			pointDrawableNoraml = getResources().getDrawable(
					R.drawable.point_normal);
		};
		if (pointDrawableSelect == null) {
			pointDrawableSelect = getResources().getDrawable(
					R.drawable.point_select);
		}
		a.recycle();
	}
	private void initView() {
		LayoutInflater.from(context).inflate(R.layout.shuffling_picture,this);
		imageViewPager = (ViewPager) findViewById(R.id.shuffling_viewpage);
		pointLinearLayout = (LinearLayout) findViewById(R.id.shuffling_point_layout);
	}

	private void setViewPageAdapter(AdapterCycle pagerAdapter) {
		this.pagerAdapter = pagerAdapter;
		imageViewPager.setOnPageChangeListener(this);
		imageViewPager.setAdapter(pagerAdapter);
		imageViewPager.setOffscreenPageLimit(views.size());
		imageViewPager.setCurrentItem(1);
		imageViewPager.setOnTouchListener(this);
		startShuffling();
	};

	public void setViews(LinkedList<View> listViews) {
		views = listViews;
		initPoints();
		setViewPageAdapter(new AdapterCycle(context, views));
	}

	// 实现ViewPager.OnPageChangeListener接口
	@Override
	public void onPageSelected(int position) {
		if (pagerAdapter.getCount() > 1) { // 多于1，才会循环跳转
			if (position < 1) { // 首位之前，跳转到末尾（N）
				position = views.size(); // 注意这里是mList，而不是mViews
				imageViewPager.setCurrentItem(position, false);
			} else if (position > views.size()) { // 末位之后，跳转到首位（1）
				imageViewPager.setCurrentItem(1, false); // false:不显示跳转过程的动画
				position = 1;
			} else {
				setCurDot(position - 1);
			}
		}

	}

	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (isPlay) {
				if (pointIndex < views.size() + 1) {
					pointIndex++;
				} else {
					pointIndex = 0;
				}
				imageViewPager.setCurrentItem(pointIndex);
				if (pointIndex < 1) { // 首位之前，跳转到末尾（N）
					pointIndex = views.size(); // 注意这里是mList，而不是mViews
					imageViewPager.setCurrentItem(pointIndex, true);
				} else if (pointIndex > views.size()) { // 末位之后，跳转到首位（1）
					imageViewPager.setCurrentItem(1, false); // false:不显示跳转过程的动画
					pointIndex = 1;
				} else {
					setCurDot(pointIndex - 1);
				}
			}
			handler.postDelayed(this, 3000);
		}
	};

	private void startShuffling() {
		handler.postDelayed(runnable, 3000);
	};

	private void initPoints() {
		points = new ImageView[views.size()];
		// 动态添加小点
		for (int i = 0; i < views.size(); i++) {
			LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			ImageView point_view = new ImageView(context);// new 一个ImageView
			point_view.setPadding(10, 5, 10, 5);
			point_view.setClickable(true);
			llp.gravity = Gravity.CENTER_VERTICAL;
			point_view.setImageDrawable(pointDrawableNoraml);// 设置资源
			pointLinearLayout.addView(point_view, llp); // 最后一步，添加控件到布局中
		}

		// 循环取得小点图片
		for (int i = 0; i < views.size(); i++) {
			// 得到一个LinearLayout下面的每一个子元素
			points[i] = (ImageView) pointLinearLayout.getChildAt(i);
			// 默认都设为灰色
			points[i].setEnabled(true);
			// 给每个小点设置监听
			points[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					int positions = (Integer) v.getTag();
					setCurView(positions + 1);
					setCurDot(positions);
					pointIndex = positions;
				}

			});
			// 设置位置tag，方便取出与当前位置对应
			points[i].setTag(i);
		}

		// 当只有一张图片的时候，隐藏那个小点
		if (views.size() > 1) {
			pointLinearLayout.setVisibility(View.VISIBLE);
		} else {
			pointLinearLayout.setVisibility(View.GONE);
		}

		currentIndex = 0;
		// 设置为白色，即选中状态
		points[0].setEnabled(false);
		points[0].setImageDrawable(pointDrawableSelect);

	}

	protected void setCurDot(int position) {
		if (position < 0 || position > views.size() - 1
				|| currentIndex == position) {
			return;
		}
		points[position].setEnabled(false);
		points[position].setImageDrawable(pointDrawableSelect);// 设置资源
		points[currentIndex].setEnabled(true);
		points[currentIndex].setImageDrawable(pointDrawableNoraml);
		currentIndex = position;
	}

	protected void setCurView(int position) {
		if (position < 0) {
			return;
		}
		imageViewPager.setCurrentItem(position);
	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {
		if (isScrolling) {
			if (lastValue > positionOffsetPixels) {
				// 递减，向右侧滑动
				right = true;
				left = false;
			} else if (lastValue < positionOffsetPixels) {
				// 递减，向右侧滑动
				right = false;
				left = true;
			} else if (lastValue == positionOffsetPixels) {
				right = left = false;
			}
		}
		lastValue = positionOffsetPixels;
	}

	@Override
	public void onPageScrollStateChanged(int state) {
		if (state == 1) {
			isScrolling = true;
		} else {
			isScrolling = false;
		}

		if (state == 2) {
			if (changeViewCallback != null) {
				changeViewCallback.changeView(left, right);
			}
			right = left = false;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			isPlay = false;
			break;
		case MotionEvent.ACTION_UP:
			isPlay = true;
			if (right) {
				pointIndex = currentIndex;
			}
			if (left) {
				pointIndex = currentIndex + 1;
			}
			break;
		default:
			break;
		}
		return false;
	}

	/**
	 * 得到是否向右侧滑动
	 * 
	 * @return true 为右滑动
	 */
	public boolean getMoveRight() {
		return right;
	}

	/**
	 * 得到是否向左侧滑动
	 * 
	 * @return true 为左做滑动
	 */
	public boolean getMoveLeft() {
		return left;
	}

	/**
	 * 滑动状态改变回调
	 * 
	 * @author fuxingkai
	 * 
	 */
	public interface ChangeViewCallback {
		/**
		 * 切换视图 ？决定于left和right 。
		 * 
		 * @param left
		 * @param right
		 */
		public void changeView(boolean left, boolean right);
	}

	/**
	 * set ...
	 * 
	 * @param callback
	 */
	public void setChangeViewCallback(ChangeViewCallback callback) {
		changeViewCallback = callback;
	}

	public class AdapterCycle extends PagerAdapter {
		private LinkedList<View> mViews; // 新view集合

		public AdapterCycle(Context context, LinkedList<View> mOldViews) {
			if (mOldViews != null) {
				// 无论是否多于1个，都要初始化第一个（index:0）
				mViews = new LinkedList<View>();

				final ImageView view = (ImageView) mOldViews.get(mOldViews.size() - 1);
				ImageView imageView = new ImageView(context);
				imageView.setImageDrawable(view.getDrawable());
				mViews.add(imageView);
				// 注意，如果不只1个，mViews比mList多两个（头尾各多一个）
				// 假设：mList为mList[0~N-1], mViews为mViews[0~N+1]
				// mViews[0]放mList[N-1], mViews[i]放mList[i-1],
				// mViews[N+1]放mList[0]
				// mViews[1~N]用于循环；首位之前的mViews[0]和末尾之后的mViews[N+1]用于跳转
				// 首位之前的mViews[0]，跳转到末尾（N）；末位之后的mViews[N+1]，跳转到首位（1）
				if (mOldViews.size() > 1) { // 多于1个要循环
					for (int i = 0; i < mOldViews.size(); i++) { // 中间的N个（index:1~N）
						final View view1 = mOldViews.get(i);
						mViews.add(view1);
					}
					// 最后一个（index:N+1）
					final ImageView view2 = (ImageView) mOldViews.get(0);
					ImageView imageView1 = new ImageView(context);
					imageView.setImageDrawable(view2.getDrawable());
					mViews.add(imageView1);
				}
			}
		}

		@Override
		public int getCount() {
			return mViews.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			((ViewPager) container).removeView(mViews.get(position));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = mViews.get(position);
			container.addView(view);
			return view;
		}
	}

	

}
